<template>
    <!--地图挂载dom-->
    <div id="map" ref="mapRef">
    </div>
</template>

<script>
    //引入依赖
    import {Map, View} from 'ol'
    import {OSM} from 'ol/source'
    import {Tile as TileLayer} from 'ol/layer';
    import Draw, {createBox, createRegularPolygon,} from 'ol/interaction/Draw';

    export default {
        name: 'ProjectExportLayer',
        data() {
            return {
                map: null,
            }
        },
        mounted() {

            //初始化地图
            this.map = new Map({
                target: 'map',//指定挂载dom，注意必须是id
                layers: [
                    new TileLayer({
                        source: new OSM()
                    })
                ],
                //配置视图
                view: new View({
                    center: [113.24981689453125, 23.126468438108688],   //视图中心位置
                    projection: "EPSG:4326", //指定投影
                    zoom: 5   //缩放到的级别
                })
            });
            this.map.getView().fit([112.950439453125, 22.510986328125, 114.06005859375, 23.939208984375], this.map.getSize());
            this.addDraw("Box");
        },
        methods: {
            // 反转遮罩层
            addDraw(type) {
                if (type !== 'None') {
                    let geometryFunction;
                    if (type === 'Square') {
                        type = 'Circle';
                        geometryFunction = createRegularPolygon(4);
                    } else if (type === 'Box') {
                        type = 'Circle';
                        geometryFunction = createBox();
                    } else if (type === 'Star') {
                        type = 'Circle';
                        geometryFunction = function (coordinates, geometry) {
                            const center = coordinates[0];
                            const last = coordinates[coordinates.length - 1];
                            const dx = center[0] - last[0];
                            const dy = center[1] - last[1];
                            const radius = Math.sqrt(dx * dx + dy * dy);
                            const rotation = Math.atan2(dy, dx);
                            const newCoordinates = [];
                            const numPoints = 12;
                            for (let i = 0; i < numPoints; ++i) {
                                const angle = rotation + (i * 2 * Math.PI) / numPoints;
                                const fraction = i % 2 === 0 ? 1 : 0.5;
                                const offsetX = radius * fraction * Math.cos(angle);
                                const offsetY = radius * fraction * Math.sin(angle);
                                newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
                            }
                            newCoordinates.push(newCoordinates[0].slice());
                            if (!geometry) {
                                geometry = new Polygon([newCoordinates]);
                            } else {
                                geometry.setCoordinates([newCoordinates]);
                            }
                            return geometry;
                        };
                    }
                    //添加绘制交互事件
                    this.draw = new Draw({
                        type: type,//绘制的几何图形的几何类型
                        clickTolerance: 6,//点击公差
                        source: this.source,
                        geometryFunction: geometryFunction,
                        wrapX: true
                    });
                    this.map.addInteraction(this.draw);
                    //绘制结束导出地图
                    this.draw.on("drawend", this.exportImg)
                }
            },
            exportImg(evt) {
                //导出图片
                let feature = evt.feature;//绘制的要素
                let extent = feature.getGeometry().getExtent();//要素的范围
                console.log(extent);
                //地理坐标转换屏幕坐标
                let coord1 = [extent[0], extent[3]];
                let leftTopPosition = this.map.getPixelFromCoordinate(coord1);
                //地理坐标转换屏幕坐标
                let coord2 = [extent[2], extent[1]];
                let bottomRightPosition = this.map.getPixelFromCoordinate(coord2);
                console.log(leftTopPosition);
                console.log(bottomRightPosition);
                //计算框选矩形的宽度以及高度像素
                let width = Math.abs(bottomRightPosition[0] - leftTopPosition[0]);
                let height = Math.abs(bottomRightPosition[1] - leftTopPosition[1]);
                console.log(width);
                console.log(height);
                //计算框选矩形的左上角屏幕坐标,放置用户反过来绘制
                let minx = leftTopPosition[0] <= bottomRightPosition[0] ? leftTopPosition[0] : bottomRightPosition[0];
                let miny = leftTopPosition[1] <= bottomRightPosition[1] ? leftTopPosition[1] : bottomRightPosition[1];
                console.log(minx);
                console.log(miny);
                let canvas = document.getElementsByTagName('canvas')[0];
                let ctx = canvas.getContext("2d");
                let img = ctx.getImageData(minx, miny, width, height);
                console.log(img);
                //创建一个canvas
                let drawCanvas = document.createElement("canvas");
                drawCanvas.width = width;
                drawCanvas.height = height;
                //将上面获取到的imageData放到创建的canvas中
                let context = drawCanvas.getContext("2d");
                context.putImageData(img, 0, 0);
                //将图像转成base64编码
                let toDataURL = drawCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                console.log(toDataURL);
                //创建a标签进行点击下载
                let link = document.createElement('a');
                link.download = '框选导出.png';
                link.href = toDataURL;
                link.click();
            }
        }
    }
</script>

<style scoped>
    #map {
        width: 100%;
        height: 100%;
    }
</style>
